package com.example.wechat.controller;

import com.example.wechat.enums.PayStates;
import com.example.wechat.pojo.pay.Order;
import com.example.wechat.service.OrderServiceI;
import com.example.wechat.service.impl.OrderServiceImpl;
import com.example.wechat.utils.GenerateQRCodeUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.configurationprocessor.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Controller
public class TestController {
    @Autowired
    OrderServiceImpl serviceI;

    @CrossOrigin
    @ResponseBody
    @RequestMapping("/test2")
    public String test2(HttpServletResponse response){
        System.out.println("aa");
        Collection<String> headerNames = response.getHeaderNames();
        for (String name:headerNames){
            System.out.println(name);
        }
        return "aadf";
    }

    @RequestMapping("/shop")
    public String goToShop(HttpSession session){
        //登录时，就初始化
        session.setAttribute("orders",new HashMap<String,Order>());
        return "shop";
    }
    @RequestMapping("/buy")
    public ModelAndView buy(Order order, ModelAndView model, HttpSession session) throws Exception {
        System.out.println(order);
        String code_url = serviceI.createOrderByNativePay(order);
        //获取该用户的当前的所有订单
        Map<String,Order> orders = (Map<String, Order>) session.getAttribute("orders");
        //将这次购买的订单也加入其中
        orders.put(order.getOrderNumber(),order);
        //生成二维码
        byte[] bytesImg = GenerateQRCodeUtil.generateQRCode(code_url, 360, 360);
        String imageBase64 = new BASE64Encoder().encode(bytesImg);
        model.addObject("QRCode",imageBase64);
        model.addObject("orderNumber",order.getOrderNumber());
        model.setViewName("buy");

        return model;
    }
    //由于没有证书，所以只能这样写下单成功回调
    @ResponseBody
    @RequestMapping("/success")
    public boolean checkBuySuccess(@RequestBody String orderNumber,HttpSession session){
        Map<String,Order> orders = (Map<String, Order>) session.getAttribute("orders");
        Order order = orders.get(orderNumber);
        while(true){
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            PayStates payStates = serviceI.queryOrder(order);
            if(PayStates.SUCCESS.equals(payStates)){
                System.out.println("支付成功");
                return true;
            }else if (PayStates.CLOSED.equals(payStates)){
                System.out.println("订单已经关闭");
                return false;
            }else{
                System.out.println(payStates.getTradeStateDesc());
            }
        }
    }


    @ResponseBody
    @RequestMapping("/flush")
    public String flushQRCode(@RequestBody String orderNumber,HttpSession session) throws Exception {
        //获取该用户的当前的所有订单
        Map<String,Order> orders = (Map<String, Order>) session.getAttribute("orders");
        Order order = orders.get(orderNumber);
        byte[] bytesImg = GenerateQRCodeUtil.generateQRCode(order.getCodeUrl()+"&"+new Date().getTime(), 360, 360);
        String encode = new BASE64Encoder().encode(bytesImg);
        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(encode);
        return json;
    }



}
